package club.gggd.qqrobot.listener;

import cn.hutool.http.HttpUtil;
import love.forte.simboot.annotation.Filter;
import love.forte.simboot.annotation.Listener;
import love.forte.simboot.filter.MatchType;
import love.forte.simbot.event.GroupMessageEvent;
import love.forte.simbot.message.Image;
import love.forte.simbot.resources.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;


/**
 * @Description 随机图片
 * @Author srx
 * @date 2022/9/6 16:18
 */
@Component
public class RandomImgListener {

    @Value("${path.random-picture.url}")
    private String url;

    @Value("${path.random-picture.path}")
    private String basePath;

    private final String SUFFIX = ".jpg";

    @Listener
    @Filter(value = "图片", matchType = MatchType.TEXT_EQUALS)
    public void listen(GroupMessageEvent event) {
        OutputStream os = null;
        try {
            long s = System.currentTimeMillis();
            String path = basePath + File.separatorChar + s + SUFFIX;
            os = new FileOutputStream(path);
            HttpUtil.download(url, os, true);
            File file = new File(path);
            Image<?> image = event.getBot().uploadImageBlocking(Resource.of(file));
            event.getGroup().sendBlocking(image);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
